// 业务逻辑处理
// const data = require('./data.json');
const fs = require('fs');
const db = require('./db.js');
const path = require('path');


// 渲染主页面
exports.showIndex = (req, res) => {
  let sql = 'select * from book';
  db.base(sql, null, (results) => {
    res.render('index', {
      list : results
    })
  })
  
}

// 渲染添加图书页面
exports.toAddBook = (req, res) => {
  res.render('addBook', {})
}

// 添加图书
exports.addBook = (req, res) => {
  let info = req.body;
  // console.log(info)
  // let book = {};
  // for (let key in info) {
  //   book[key] = info[key];
  // }

  let sql = 'insert into book set?';
  db.base(sql, info, (results) => {
    if (results.affectedRows == 1) {
      res.redirect('/');
    }
  })
}
// 跳转到编辑图书页面
exports.toEditBook = (req, res) => {
  let id = req.query.id;
  console.log(id)
  let sql = 'select * from book where id=? ';
  let data = [id];
  db.base(sql, data, (results) => {
    res.render('editBook', results[0]); 
  })
}

// 提交编辑后的页面
exports.editBook = (req, res) => {
  let info = req.body;
  let sql = 'update book set name=?,author=?,category=?,description=? where id=?';
  let data = [info.name, info.author, info.category, info.description, info.id];
  db.base(sql, data, (results) => {
    if (results.affectedRows == 1) {
      res.redirect('/')
    }
  })
}
// 删除操作
exports.deleteBook = (req, res) => {
  let id = req.query.id;
  let sql = 'delete from book where id=?';
  let data = [id];
  db.base(sql, data, (results) => {
    res.redirect('/')
  })
}